import { defineConfig, loadEnv } from 'vite';
import { fileURLToPath, URL } from 'node:url'
import fs from 'fs';
import path from 'path';
import vue from '@vitejs/plugin-vue';
import monkey, { cdn, util } from 'vite-plugin-monkey';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite'
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd());
  const configFileName = env.VITE_APP_NAME;
  const configFilePath = path.join(process.cwd(), 'src/appConfig', `${configFileName}.json`);
  const componentsPath = path.join(process.cwd(), 'src/components', `${configFileName}.vue`);
  let appConfig = {};
  try {
    fs.statSync(componentsPath);
    appConfig = JSON.parse(fs.readFileSync(configFilePath, 'utf-8'));
  } catch (error) {
    console.error(`目标app组件或配置文件不存在`, error);
    process.exit(1)
  }
  let userscript = {
    name: appConfig.name || env.VITE_APP_NAME,
    description: appConfig.description || env.VITE_APP_DESCRIPTION,
    author: appConfig.author || env.VITE_APP_AUTHOR,
    icon: appConfig.icon || env.VITE_APP_ICON,
    namespace: env.VITE_APP_NAMESPACE,
    match: appConfig.match
  }
  console.log(userscript);
  return {
    plugins: [
      vue(),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/ // .md
        ],
        imports: ['vue', util.unimportPreset],
      }),
      Components({
        dirs: ['src/components'],
        extensions: ['vue'],
      }),
      monkey({
        entry: 'src/main.js',
        userscript: userscript,
        build: {
          fileName: `${appConfig.name || env.VITE_APP_NAME}.user.js`,
          externalGlobals: {
            vue: cdn.jsdelivr('Vue', 'dist/vue.global.prod.js'),
          },
        },
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
  }
});
